package com.kfm.hotel.interceptor;

import com.kfm.hotel.anno.Permission;
import com.kfm.hotel.domain.SysMenu;
import com.kfm.hotel.util.Constant;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;

public class MenuInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Annotation annotation = method.getAnnotation(Permission.class);
        if (annotation != null){
            Set<String> permission = (Set<String>) request.getSession().getAttribute(Constant.LOGIN_USER_PERMISSION);
            // 有 Permission 注解，需要进行权限校验
            Permission permissionAnnotation = (Permission) annotation;
            String value = permissionAnnotation.value();
            if (permission.contains(value)){
                return true;
            }
            // 抛一个未授权访问异常
            throw new RuntimeException("未授权访问");
        }
        return true;
//        if (permission != null){
//            for(SysMenu menu : permission){
//                if (uri.equals(menu.getUrl())){
//                    return true;
//                }
//            }
//        }
//        response.sendRedirect("/login");
//        return false;
    }
}
